'use client';
import { useRouter } from 'next/navigation';
import { useEffect, useState, use } from 'react';
import { Spinner } from '@/components/ui/Spinner';
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { useLanguage } from '@/contexts/LanguageContext';
import { useSession } from 'next-auth/react';
import { useToast } from "@/hooks/use-toast"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

export default function SharePromptDetail({ params }) {
  const resolvedParams = use(params);
  const { id } = resolvedParams;
  const { language, t } = useLanguage();
  const { data: session } = useSession();
  const { toast } = useToast();
  const [prompt, setPrompt] = useState(null);
  const [copySuccess, setCopySuccess] = useState(false);
  const [copyIdSuccess, setCopyIdSuccess] = useState(false);
  const [selectedVersion, setSelectedVersion] = useState('');
  const [dateFilter, setDateFilter] = useState('');
  const router = useRouter();

  useEffect(() => {
    if (id) {
      fetch(`/api/share/${id}`)
        .then((response) => response.json())
        .then((data) => {
          const promptData = {...data, tags: data.tags ? data.tags.split(',') : []};
          setPrompt(promptData);
          setSelectedVersion(promptData.version || '1.0.0');
        })
        .catch((error) => console.error('Error fetching prompt:', error));
    }
  }, [id]);

  const handleVersionChange = (newVersion) => {
    setSelectedVersion(newVersion);
    // 这里可以根据版本筛选逻辑进行处理
    // 如果有对应的版本ID，可以跳转到对应页面
    if (prompt.versions) {
      const versionData = prompt.versions.find(v => v.version === newVersion);
      if (versionData && versionData.id !== id) {
        router.push(`/share/${versionData.id}`);
      }
    }
  };

  const handleDateFilterChange = (dateRange) => {
    setDateFilter(dateRange);
    // 这里可以添加日期筛选逻辑
  };

  if (!t) return <div className="flex justify-center items-center h-64"><Spinner /></div>;
  const tp = t.sharePage;
  if (!tp) return <div className="flex justify-center items-center h-64"><Spinner /></div>;

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(prompt.content);
      setCopySuccess(true);
      setTimeout(() => setCopySuccess(false), 2000);
    } catch (err) {
      console.error('Failed to copy text:', err);
    }
  };

  const handleCopyId = async () => {
    try {
      await navigator.clipboard.writeText(id);
      setCopyIdSuccess(true);
      setTimeout(() => setCopyIdSuccess(false), 2000);
    } catch (err) {
      console.error('Failed to copy ID:', err);
    }
  };

  const handleCopyToWorkspace = () => {
    // 直接跳转到对应的提示词页面
    router.push(`/prompts/${id}`);
  };

  if (!prompt) {
    return (
      <div className="flex justify-center items-center h-64">
        <Spinner />
      </div>
    );
  }

  // 格式化创建时间
  const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  return (
    <div className="container mx-auto px-4 py-8 max-w-4xl">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900 mb-6">{prompt.title}</h1>
        {prompt.description && (
          <div className="flex items-start gap-2">
            <span className="font-medium text-gray-700">描述：</span>
            <p className="text-gray-600 flex-1">{prompt.description}</p>
          </div>
        )}
      </div>

      {/* 筛选控件区域 */}
      <div className="flex flex-wrap gap-4 mb-6">
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-600">📅</span>
          <span className="text-sm text-gray-700">{formatDate(prompt.created_at) || '2025/5/19'}</span>
        </div>
        
        <div className="flex items-center gap-2">
          <span className="text-sm text-gray-600">📋</span>
          <Select value={selectedVersion} onValueChange={handleVersionChange}>
            <SelectTrigger className="w-32 h-8">
              <SelectValue placeholder="版本" />
            </SelectTrigger>
            <SelectContent>
              {(() => {
                // 获取所有版本并排序（从大到小）
                const allVersions = [
                  { id: id, version: prompt.version || '1.0.0' },
                  ...(prompt.versions || [])
                ];
                // 去重并按版本号从大到小排序
                const uniqueVersions = allVersions
                  .filter((version, index, self) => 
                    index === self.findIndex(v => v.version === version.version)
                  )
                  .sort((a, b) => {
                    // 简单的字符串比较，从大到小
                    return b.version.localeCompare(a.version, undefined, { numeric: true });
                  });
                
                return uniqueVersions.map((version) => (
                  <SelectItem key={version.id} value={version.version}>
                    Version {version.version}
                  </SelectItem>
                ));
              })()}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 标签区域 */}
      {prompt.tags && prompt.tags.length > 0 && (
        <div className="flex items-center flex-wrap gap-2 mb-6">
          <span className="text-sm font-medium text-gray-700">标签：</span>
          {prompt.tags.map((tag, index) => (
            <Badge key={index} variant="secondary">
              {tag}
            </Badge>
          ))}
        </div>
      )}

      {/* 提示词内容区域 */}
      <Card className="mb-6">
        <CardContent className="p-0">
          {/* 提示词内容抬头 */}
          <div className="flex items-center justify-between p-4 border-b bg-gray-50">
            <h2 className="text-lg font-semibold text-gray-900">提示词内容</h2>
            <div className="flex gap-3">
              <Button onClick={handleCopyId} variant="outline">
                🆔 {copyIdSuccess ? "已复制!" : "复制提示词ID"}
              </Button>
              <Button onClick={handleCopy} variant="outline">
                📋 {copySuccess ? "已复制!" : "复制提示词内容"}
              </Button>
              <Button 
                onClick={handleCopyToWorkspace} 
                className="bg-black text-white hover:bg-gray-800"
              >
                💼 复制到工作区
              </Button>
            </div>
          </div>
          
          {/* 提示词内容 */}
          <div className="p-6">
            <div className="bg-gray-50 p-4 rounded-lg">
              <pre className="whitespace-pre-wrap text-sm text-gray-800 font-mono leading-relaxed">
                {prompt.content}
              </pre>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
} 